<?php
namespace Modules\Home;

use Phalcon\DiInterface;
use Phalcon\Mvc\Dispatcher;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface {

  /**
   * Register a specific autoloader for the module
   *
   * @param DiInterface $di
   */
  public function registerAutoloaders(DiInterface $di = null) {
    (new \Phalcon\Loader()) -> registerNamespaces([
      'Phalcon\\Paginator' => BASE_PATH . 'vendor/phalcon/incubator/Library/Phalcon/Paginator/',

      'Common'     => SRC_PATH . 'common/',
      'Components' => SRC_PATH . 'components/',

      __NAMESPACE__ . '\\Controllers' => __DIR__ . '/controllers/',
      __NAMESPACE__ . '\\Libraries' => __DIR__ . '/libraries/',
      __NAMESPACE__ . '\\Services' => __DIR__ . '/services/',
      __NAMESPACE__ . '\\Validations' => __DIR__ . '/validations/'
    ]) -> register();
  }

  /**
   * Register specific services for the module
   *
   * @param DiInterface $di
   */
  public function registerServices(DiInterface $di) {
      /*
    $di -> set('security', function() {
      return (new \Phalcon\Security()) -> setWorkFactor(8);
    });
    */

    $di -> set('session', function() {
            $session = new \Phalcon\Session\Adapter\Files();
        $session -> start();
            return $session;
        }
    );

    $di -> set('config', function() {
      return new \Phalcon\Config(require __DIR__ . '/config/config.php');
    });

    // Registering a dispatcher
    $di -> set('dispatcher', function() {
      $dispatcher = new \Phalcon\Mvc\Dispatcher();

      //$eventManager = new \Phalcon\Events\Manager();

      // Attach a event listener to the dispatcher (if any)
            // For example:
            // $eventManager->attach('dispatch', new \My\Awesome\Acl('frontend'));

      //$dispatcher -> setEventsManager($eventManager);
      $dispatcher -> setDefaultNamespace(__NAMESPACE__ . '\\Controllers');
      return $dispatcher;
    });

    $di -> set('backendCache', function() {
      $filename = BASE_PATH . 'runtime/cache/';
      if(!is_dir($filename)) {
        mkdir($filename, 0777, true);
      }

      return new \Phalcon\Cache\Backend\File(
        \Phalcon\Cache\Frontend\Factory::load([
          'lifetime' => 86400,
          'adapter' => 'data'
        ]),
        [
          'cacheDir' => $filename
        ]
      );
    });

    // Registering the view component
    $di -> set('view', function() {
      return (new \Phalcon\Mvc\View())
        -> setViewsDir(__DIR__ . DS . 'views')
        -> setLayoutsDir(__DIR__.DS.'views'.DS.'layouts'.DS);
    });

    $di -> set('user', function() {
      return \Components\Account\Factory::load([
        'adapter' => 'User',
        'di' => \Phalcon\Di::getDefault()
      ]);
    }, false);
  }
}